﻿using Microsoft.AspNetCore.Mvc.Razor;
using System.Collections.Generic;
using System.Linq;

namespace Basefr.Web.Razor
{
    public class SubAreaViewLocationExpander : IViewLocationExpander
    {
        public const string SubAreaRouteKey = "subarea";

        public void PopulateValues(ViewLocationExpanderContext context)
        {
            if (context.ActionContext.ActionDescriptor.RouteValues.TryGetValue(SubAreaRouteKey, out var subArea))
            {
                context.Values[SubAreaRouteKey] = subArea;
            }
        }

        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            if (context.ActionContext.RouteData.Values.ContainsKey(SubAreaRouteKey))
            {
                var subArea = RazorViewEngine.GetNormalizedRouteValue(context.ActionContext, SubAreaRouteKey);
                var subAreaViewLocation = new[] { "/Areas/{2}/" + subArea + "/Views/{1}/{0}.cshtml" };

                viewLocations = subAreaViewLocation.Concat(viewLocations);
            }

            return viewLocations;
        }
    }
}
